import { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { DataSource } from 'typeorm';

@Injectable()
export class AppService implements OnApplicationShutdown {

  constructor(
    @Inject(REQUEST) private request: Request,
    @Inject('TYPEORM_CONNECTS') private connections: Map<string, DataSource>
  ) {}

  // 用于在app关闭时销毁多数据库连接共用实列
  onApplicationShutdown(signal?: string) {
    if(this.connections.size > 0) {
      for (const key of this.connections.keys()) {
        this.connections.get(key)?.destroy()
      }
    }
  }

  getHello(): string {
    return 'Hello World!';
  }

  getDBConfig(): any {
    const headers = this.request.headers
    const tenantId = headers['x-tenant-id']

    if(tenantId == 'mysql1') {
      return {
        port: 3306
      }
    } else if(tenantId == 'postgresql') {
      return {
        type: 'postgresql',
        port: 5432,
        usename: 'pguser',
        database: 'testdb'
      }
    }

    return {
      port: 3307
    }
  }
}
